import Vue from 'vue'
const state = {
  isGetAuth: false
}

const getters = {
  getIsGetAuth: state => {
    return state.isGetAuth
  }
}

const mutations = {
  muIsGetAuth () {
    state.isGetAuth = !state.isGetAuth
  },
  muFalseAuth () {
    state.isGetAuth = false
  }
}

const actions = {
  actUserMenuAndFun ({ commit }, payload) {
    return new Promise((resolve, reject) => {
      const plugData = Vue.prototype.$getCookie('plugData')
      const currentUser = Vue.prototype.$getCookie('currentUser')
      if (plugData) {
        const {plugId, authority, plugNo} = JSON.parse(plugData)
        const {type} = JSON.parse(currentUser)
        // 下个界面是否需要获取权限
        if (authority === 1 && payload.routeTo.path.includes(plugNo)) {
          const data = {
            'query.plug_id': plugId,
            'query.fun_type': type
          }
          Vue.prototype.$axios({
            method: 'post',
            data: Vue.prototype.$qs.stringify(data),
            url: `${Vue.prototype.$site.companyServer}/front/findUserMenu.htm`
          }).then(res => {
            if (res.data.errorMsg) {
              Vue.prototype.$message.error(res.data.errorMsg)
              reject('noAuthority')
              return
            }
            if (res.data.fun) {
              const {list} = res.data.fun
              if (list && list.length > 0) {
                let href = ''
                const menus = list.map((item, index) => {
                  if (index === 0) {
                    Vue.prototype.$local.set('childMenus', item.childMenu)
                    if (list[0].menuCode) {
                      href = item.childMenu[0].menuCode
                    }
                  }
                  item.childMenu.forEach((fun, e) => {
                    if (index === 0 && e === 0) {
                      Vue.prototype.$local.set('funs', fun.childMenu)
                    }
                  })
                  return item
                })
                Vue.prototype.$local.set('menus', menus)
                commit('muIsGetAuth')
                resolve(href)
              } else {
                resolve('noAuthority')
              }
            }
          })
        } else {
          resolve()
        }
      } else {
        resolve()
      }
    })
  }
}

export default {
  state,
  getters,
  mutations,
  actions
}
